import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/favorite_provider.dart';
import '../../domain/entities/anime.dart';
import '../../domain/entities/favorite.dart';

/// 可重用的收藏按钮组件
class FavoriteButton extends StatefulWidget {
  final Anime anime;
  final bool showLabel;
  final VoidCallback? onFavoriteChanged;

  const FavoriteButton({
    super.key,
    required this.anime,
    this.showLabel = false,
    this.onFavoriteChanged,
  });

  @override
  State<FavoriteButton> createState() => _FavoriteButtonState();
}

class _FavoriteButtonState extends State<FavoriteButton> {
  bool _isFavorite = false;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _checkFavoriteStatus();
  }

  Future<void> _checkFavoriteStatus() async {
    final provider = Provider.of<FavoriteProvider>(context, listen: false);
    final isFavorite = await provider.isFavorite(widget.anime.id);
    setState(() {
      _isFavorite = isFavorite;
    });
  }

  Future<void> _handleFavoriteToggle() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    final provider = Provider.of<FavoriteProvider>(context, listen: false);
    
    if (_isFavorite) {
      // 已收藏，显示操作选项
      _showFavoriteOptionsDialog(provider);
    } else {
      // 未收藏，显示添加选项
      _showAddToFavoriteDialog(provider);
    }

    setState(() {
      _isLoading = false;
    });
  }

  void _showAddToFavoriteDialog(FavoriteProvider provider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加到收藏'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: FavoriteStatus.values.map((status) {
            return ListTile(
              leading: Icon(_getStatusIcon(status), color: _getStatusColor(status)),
              title: Text(status.displayName),
              onTap: () async {
                Navigator.pop(context);
                await _addToFavorite(status, provider);
              },
            );
          }).toList(),
        ),
      ),
    );
  }

  void _showFavoriteOptionsDialog(FavoriteProvider provider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('收藏选项'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.edit, color: Colors.blue),
              title: const Text('修改状态'),
              onTap: () {
                Navigator.pop(context);
                _showChangeStatusDialog(provider);
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.delete, color: Colors.red),
              title: const Text('移除收藏', style: TextStyle(color: Colors.red)),
              onTap: () async {
                Navigator.pop(context);
                await _removeFromFavorite(provider);
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showChangeStatusDialog(FavoriteProvider provider) async {
    final currentFavorite = await provider.getFavorite(widget.anime.id);
    
    if (!mounted) return;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改收藏状态'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: FavoriteStatus.values.map((status) {
            return RadioListTile<FavoriteStatus>(
              title: Text(status.displayName),
              value: status,
              groupValue: currentFavorite?.status,
              onChanged: (value) async {
                if (value != null) {
                  Navigator.pop(context);
                  await _updateFavoriteStatus(value, provider);
                }
              },
            );
          }).toList(),
        ),
      ),
    );
  }

  Future<void> _addToFavorite(FavoriteStatus status, FavoriteProvider provider) async {
    print('添加收藏：动漫ID=${widget.anime.id}, 状态=${status.displayName}');
    final success = await provider.addFavorite(widget.anime, status);
    if (success && mounted) {
      setState(() {
        _isFavorite = true;
      });
      
      widget.onFavoriteChanged?.call();
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('已添加到${status.displayName}')),
      );
    } else {
      print('添加收藏失败');
    }
  }

  Future<void> _removeFromFavorite(FavoriteProvider provider) async {
    final success = await provider.removeFavorite(widget.anime.id);
    if (success && mounted) {
      setState(() {
        _isFavorite = false;
      });
      
      widget.onFavoriteChanged?.call();
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('已移除收藏')),
      );
    }
  }

  Future<void> _updateFavoriteStatus(FavoriteStatus status, FavoriteProvider provider) async {
    final success = await provider.updateFavoriteStatus(widget.anime.id, status);
    if (success && mounted) {
      widget.onFavoriteChanged?.call();
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('状态已更新为${status.displayName}')),
      );
    }
  }

  IconData _getStatusIcon(FavoriteStatus status) {
    switch (status) {
      case FavoriteStatus.wantToWatch:
        return Icons.bookmark;
      case FavoriteStatus.watching:
        return Icons.play_circle;
      case FavoriteStatus.completed:
        return Icons.check_circle;
      case FavoriteStatus.onHold:
        return Icons.pause_circle;
      case FavoriteStatus.dropped:
        return Icons.cancel;
    }
  }

  Color _getStatusColor(FavoriteStatus status) {
    switch (status) {
      case FavoriteStatus.wantToWatch:
        return Colors.blue;
      case FavoriteStatus.watching:
        return Colors.green;
      case FavoriteStatus.completed:
        return Colors.purple;
      case FavoriteStatus.onHold:
        return Colors.orange;
      case FavoriteStatus.dropped:
        return Colors.red;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(strokeWidth: 2),
      );
    }

    if (widget.showLabel) {
      return TextButton.icon(
        onPressed: _handleFavoriteToggle,
        icon: Icon(
          _isFavorite ? Icons.favorite : Icons.favorite_border,
          color: _isFavorite ? Colors.red : Colors.grey[600],
        ),
        label: Text(
          _isFavorite ? '已收藏' : '收藏',
          style: TextStyle(
            color: _isFavorite ? Colors.red : Colors.grey[600],
          ),
        ),
      );
    }

    return IconButton(
      onPressed: _handleFavoriteToggle,
      icon: Icon(
        _isFavorite ? Icons.favorite : Icons.favorite_border,
        color: _isFavorite ? Colors.red : Colors.grey[600],
      ),
    );
  }
} 